package org.lex.dbq.view.sql.result;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.lex.jdbc.util.MetaDataHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResultSetHelper {
	private Logger log = LoggerFactory.getLogger(ResultSetHelper.class);

	public int fill(TableResultViewer pane, ResultSet rs) throws SQLException {
		Table table = pane.table;
		table.setRedraw(false);

		List<TableColumn> columns = pane.columns;
		String[] columnNames = new MetaDataHelper().getColumnNames(rs.getMetaData());
		log.debug("ResultSet columns=" + columnNames.length + ", table columns=" + columns.size());
		// add columns
		if (columns.size() < columnNames.length) {
			log.debug("add table column [" + columns.size() + ", " + columnNames.length + ")");
			for (int i = columns.size(); i < columnNames.length; i++) {
				TableColumn c = new TableColumn(table, SWT.NONE);
				columns.add(c);
			}
		} else {
			log.debug("remove table column [" + columnNames.length + ", " + columns.size() + ")");
			for (int i = columns.size() - 1; i >= columnNames.length; i--) {
				TableColumn c = columns.get(i);
				c.dispose();
				columns.remove(c);
			}
		}

		// add rows
		table.removeAll();
		List<Object[]> data = (List<Object[]>) new ArrayListHandler().handle(rs);
		for (Object[] row : data) {
			TableItem item = new TableItem(table, SWT.NONE);
			for (int i = 0; i < row.length; i++) {
				item.setText(i, String.valueOf(row[i]));
				System.out.print(row[i]);
				System.out.print('\t');
			}
			System.out.println();
		}

		for (int i = 0; i < columnNames.length; i++) {
			TableColumn c = columns.get(i);
			c.setText(columnNames[i]);
			c.pack();
		}
		table.setRedraw(true);
		return data.size();
	}
}
